package org.codehaus.activemq.transport.tcp;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.URI;
import javax.jms.JMSException;
import javax.net.ServerSocketFactory;
import org.codehaus.activemq.message.WireFormat;
import org.codehaus.activemq.transport.TransportServerChannel;
import org.codehaus.activemq.transport.TransportServerChannelFactory;

public class SfTransportServerChannelFactory
  implements TransportServerChannelFactory
{
  protected static final int BACKLOG = 500;
  private ServerSocketFactory serverSocketFactory;

  public SfTransportServerChannelFactory(ServerSocketFactory socketFactory)
  {
    this.serverSocketFactory = socketFactory;
  }

  public TransportServerChannel create(WireFormat wireFormat, URI bindAddress)
    throws JMSException
  {
    ServerSocket serverSocket = null;
    try {
      serverSocket = createServerSocket(bindAddress);
    }
    catch (IOException e) {
      JMSException jmsEx = new JMSException("Creation of ServerSocket failed: " + e);
      jmsEx.setLinkedException(e);
      throw jmsEx;
    }
    return new TcpTransportServerChannel(wireFormat, serverSocket);
  }

  protected ServerSocket createServerSocket(URI bind) throws IOException {
    String host = bind.getHost();
    host = (host == null) || (host.length() == 0) ? "localhost" : host;

    InetAddress addr = InetAddress.getByName(host);
    if (addr.equals(InetAddress.getLocalHost())) {
      return this.serverSocketFactory.createServerSocket(bind.getPort(), 500);
    }

    return this.serverSocketFactory.createServerSocket(bind.getPort(), 500, addr);
  }
}